#!/bin/bash

# APK Resign Tool - 应用启动分析模块
# 负责分析APK包名并启动应用

# 从其他模块导入函数
if [ -z "$(type -t get_build_tools_path)" ]; then
    source "$(dirname "${BASH_SOURCE[0]}")/config.sh"
fi

# 分析APK包名并启动应用
analyze_and_launch() {
    local apk_file="$1"
    
    if [ ! -f "$apk_file" ]; then
        echo "错误：APK文件未找到：$apk_file"
        return 1
    fi
    
    echo "正在分析APK文件：$apk_file"
    
    # 使用aapt获取包名
    local package_name=""
    local build_tools_path=$(get_build_tools_path)
    
    if [ -n "$build_tools_path" ] && [ -f "$build_tools_path/aapt" ]; then
        package_name=$("$build_tools_path/aapt" dump badging "$apk_file" | grep "package:" | awk -F "'" '{print $2}')
    elif command -v aapt &> /dev/null; then
        package_name=$(aapt dump badging "$apk_file" | grep "package:" | awk -F "'" '{print $2}')
    else
        echo "错误：找不到aapt工具，无法分析APK"
        return 1
    fi
    
    if [ -z "$package_name" ]; then
        echo "错误：无法获取APK的包名"
        return 1
    fi
    
    echo "APK包名：$package_name"
    
    # 获取启动Activity
    local launcher_activity=""
    
    if [ -n "$build_tools_path" ] && [ -f "$build_tools_path/aapt" ]; then
        launcher_activity=$("$build_tools_path/aapt" dump badging "$apk_file" | grep "launchable-activity" | awk -F "'" '{print $2}')
    elif command -v aapt &> /dev/null; then
        launcher_activity=$(aapt dump badging "$apk_file" | grep "launchable-activity" | awk -F "'" '{print $2}')
    fi
    
    # 检查adb是否可用
    if ! command -v adb &> /dev/null; then
        echo "错误：找不到adb工具，无法启动应用"
        return 1
    fi
    
    # 检查设备连接状态
    local device_count=$(adb devices | grep -v "List" | grep -v "^$" | wc -l)
    if [ "$device_count" -eq 0 ]; then
        echo "错误：未连接任何Android设备"
        return 1
    fi
    
    # 启动应用
    echo "正在启动应用：$package_name"
    
    if [ -n "$launcher_activity" ]; then
        echo "使用启动Activity：$launcher_activity"
        adb shell am start -n "$package_name/$launcher_activity"
    else
        echo "使用包名启动应用"
        adb shell monkey -p "$package_name" -c android.intent.category.LAUNCHER 1
    fi
    
    if [ $? -eq 0 ]; then
        echo "成功启动应用：$package_name"
        return 0
    else
        echo "启动应用失败"
        return 1
    fi
} 